<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-view"
          size="small"
          type="text"
          v-if="permission.service_info_view"
          @click.stop="handleView(scope.row, scope.index)"
          >查 看</el-button
        >
        <el-button
          icon="el-icon-edit"
          size="small"
          type="text"
          v-if="permission.service_info_edit && (scope.row.serviceAuditStatus == 0 || scope.row.serviceAuditStatus == 3) && scope.row.parentServiceNo == '0'"
          @click.stop="handleEdit(scope.row, scope.index)"
          >编 辑</el-button
        >
        <el-button icon="el-icon-menu" size="small" type="text" v-if="permission.service_menu && scope.row.serviceAuditStatus == 2 && scope.row.parentServiceNo == '0'" @click.stop="handleMenu(scope.row, scope.index)">菜单分配</el-button>
      </template>
      <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          v-if="permission.service_info_add"
          @click.stop="handleSave"
          >新 增</el-button
        >
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.service_info_delete"
          @click="handleDelete"
          >删 除
        </el-button> -->
      </template>
      <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.service_info_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.service_info_export"
          @click="handleExport"
          >导出
        </el-button>
      </template>
      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page ref="searchSerSelect" label="serviceName" value="serviceNo" :select.sync="search.serviceNo" :url="website.searchLink.serviceUrl" placeholder-text="服务商" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{}" slot="orgNoSearch">
        <select-page ref="searchOrgSelect" label="serviceName" value="serviceNo" :select.sync="search.orgNo" :url="website.searchLink.orgUrl" placeholder-text="机构" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{row}"
            slot="isCooperate">
        <el-tag type="success" :color="getColorIsCooperate(row)" effect="dark">{{ row.isCooperateName }}</el-tag>
      </template>
      <template slot-scope="{row}"
            slot="profitState">
        <el-tag type="success" :color="getColorProfitState(row)" effect="dark">{{ row.profitStateName }}</el-tag>
      </template>
      <template slot-scope="{row}"
            slot="cooperateState">
        <el-tag type="success" :color="getColorCooperateState(row)" effect="dark">{{ row.cooperateStateName }}</el-tag>
      </template>
      <template slot-scope="{row}"
            slot="settlementMode">
        <el-tag>{{row.settlementModeName}}</el-tag>
      </template>
      <template slot-scope="{row}"
            slot="serviceAuditStatus">
        <el-tag type="success" :color="getColorServiceAuditStatus(row.serviceAuditStatus)" effect="dark">{{ row.serviceAuditStatusName }}</el-tag>
      </template>
      <template slot-scope="{row}"
            slot="isAuth">
        <el-tag type="success" :color="getColorState(row)" effect="dark">{{ row.isAuthName }}</el-tag>
      </template>
      <template slot-scope="{row}"
            slot="isBankAuthName">
        <el-tag type="success" :color="getColorIsBankAuthName(row.isBankAuth)" effect="dark" v-if="row.isBankAuthName">{{ row.isBankAuthName }}</el-tag>
      </template>
      
    </avue-crud>
    <el-dialog
      class="avue-dialog"
      :title="dialogText + '服务商'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-steps :active="active" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="实名信息"></el-step>
        <el-step title="结算卡信息"></el-step>
        <el-step title="分配通道"></el-step>
        <el-step title="分润配置"></el-step>
        <el-step title="预览提交"></el-step>
      </el-steps>
      <el-divider></el-divider>

      <div v-show="active == 0">
        <basic-form :basicForm="basicForm" ref="toBasicForm" />
      </div>
      <template>
        <div v-show="active == 1">
          <main-form
            :mainForm="mainForm"
            :serviceType="basicForm.serviceType"
            ref="toMainForm"
          />
        </div>
      </template>
      <template>
        <div v-show="active == 2">
          <card-form
            :cardForm="cardForm"
            :serviceType="basicForm.serviceType"
            ref="toCardForm"
          />
        </div>
      </template>
      <template>
        <div v-show="active == 3">
          <el-transfer
            class="haruyuki-width-100 haruyuki-flex-center"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入通道名称"
            :button-texts="['取消分配', '分配通道']"
            :titles="['未分配通道', '已分配通道']"
            v-model="aisleAllot"
            :data="aisleData"
          >
          </el-transfer>
        </div>
      </template>
      <template v-if="active == 4">
        <policy-form :oem="oem" :aisleCodeList="aisleAllot" ref="toPolicyForm" />
      </template>
      <template v-if="active == 5">
        <service-preview :serviceData="serviceData"/>
      </template>
      <el-alert
        v-if="basicForm.auditResult && dialogType == 'edit'"
        title="审核备注："
        :description="basicForm.auditResult"
        type="error">
      </el-alert>
      <span slot="footer" class="dialog-footer">
        <el-button
          icon="el-icon-top"
          size="small"
          type="primary"
          v-preventClick
          @click="handlePageUp"
          v-if="active != 0"
          >上一页</el-button
        >
        <el-button :icon="dialogSubmitBtnText == '下一页'?'el-icon-bottom':'el-icon-check'" size="small" @click="handlePageDown" v-preventClick>{{dialogSubmitBtnText}}</el-button>
      </span>
    </el-dialog>
    <el-dialog title="服务商菜单分配"
               append-to-body
               :visible.sync="dialogMenuVisible"
               width="450px">
      <menu-grant ref="toMenuGrant" />
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogMenuVisible = false">取 消</el-button>
        <el-button size="small" type="primary" v-preventClick @click="menuSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  getAuthDetail,
  getBankDetail,
  getAisleOemList,
  add,
  authAdd,
  bankAdd,
  // aisleAdd,
  // policyAdd,
  policyUpdateAll,
  update,
  authUpdate,
  bankUpdate,
  // aisleUpdate,
  // policyUpdate,
  getFinish,
  getExport,
  getExportTemplate,
  remove,
} from "@/api/rb-oem/serviceinfo/service_info";
import { getServiceDetail } from "@/api/rb-oem/serviceinfo/service_info_details";

// import {getRole, grantTree} from "@/api/system/role";
import { mapGetters } from "vuex";
// import { getToken } from "@/util/auth";
import { isMobile } from "@/util/validate";
import { submitMenu } from "@/api/system/menu";
import { downloadFileExcel } from "@/util/util";

import menuGrant from '@/components/rb-service/menu-grant';
import basicForm from "@/components/rb-service/basic-form";
import mainForm from "@/components/rb-service/main-form";
import cardForm from "@/components/rb-service/card-form";
import policyForm from "@/components/rb-service/policy-form";
import servicePreview from "@/components/rb-service/service-preview";
import selectPage from "@/components/select-page/select-page";

export default {
  components: {
    basicForm,
    mainForm,
    cardForm,
    policyForm,
    servicePreview,
    menuGrant,
    selectPage
  },
  data() {
    const serviceTypeValidate = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入参数"));
      } else if (isNaN(value)) {
        callback(new Error("请输入数字型参数"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!isMobile(value)) {
        callback(new Error("手机号码不正确！"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      search: {},
      dialogMenuVisible: false,
      dialogVisible: false,
      dialogType: "", //打开类型 add/edit
      dialogText: "",
      dialogSubmitBtnText: '下一页',
      active: 0,
      openType: "", //打开dialog弹框的类型
      serviceNo: "",
      userType: "2",
      props: {
        //菜单权限数据 props
        label: "title",
        value: "key",
        disabled: this.isDisabledFn,
      },
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        serviceKind: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        searchLabelWidth: 110, //搜索框标题宽度
        // searchIcon:true,
        column: [
          {
            label: "服务商编号",
            searchLabel: "服务商",
            prop: "serviceNo",
            type: 'select',
            addDisplay: false,
            editDisplay: false,
            search: true,
            span: 24,
            overHidden: true,
            width: 110,
            rules: [
              {
                required: true,
                message: "请选择服务商",
                trigger: "blur",
              },
            ],
          },
          {
            label: "服务商名称",
            labelWidth: 100,
            prop: "serviceName",
            span: 12,
            rules: [
              {
                required: true,
                message: "请输入服务商名称",
                trigger: "blur",
              },
            ],
            overHidden: true,
            minWidth: 170
          },
          {
            label: '',
            prop: 'isSelectChild',
            type: 'select',
            multiple: false,
            dataType: "string",
            showColumn: false,
            hide: true,
            search: true,
            searchType:"checkbox",
            // searchSpan:2,
            searchLabelWidth: '0',
            dicData: [{
              label:'包含下级',
              value: 1
            }]
          },
          {
            label: "所属机构",
            prop: "orgNo",
            type: "select",
            dataType: "string",
            showColumn: false,
            search: true,
            filterable: true,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择所属机构",
                trigger: "blur",
              },
            ],
          },
          {
            label: "上级服务商编号",
            prop: "parentServiceNo",
            addDisplay: false,
            editDisplay: false,
            span: 24,
            overHidden: true,
            minWidth: 120
          },
          {
            label: "上级服务商",
            labelWidth: 100,
            prop: "parentServiceName",
            span: 12,
            rules: [
              {
                required: true,
                message: "请输入上级服务商",
                trigger: "blur",
              },
            ],
            overHidden: true,
            minWidth: 170
          },
          {
            label: "服务商类型",
            labelWidth: 100,
            prop: "serviceType",
            type: "select",
            dataType: "number",
            span: 12,
            search: true,
            showColumn: false,
            slot: true,
            hide: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=service_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                validator: serviceTypeValidate,
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "服务商类型",
            prop: "serviceTypeName",
            slot: true,
            display: false,
            overHidden: true,
            minWidth: 82
          },
          {
            label: "联系人",
            prop: "contactName",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入联系人",
                trigger: "blur",
              },
            ],
            overHidden: true,
            minWidth: 75
          },
          {
            label: "联系电话",
            prop: "contactNumber",
            search: true,
            rules: [
              {
                required: true,
                validator: validatePhone,
                trigger: "blur",
              },
            ],
            overHidden: true,
            minWidth: 100
          },
          {
            label: "省份",
            prop: "provinceName",
            slot: true,
            display: false,
            overHidden: true,
            hide: true,
          },
          {
            label: "地市",
            prop: "cityName",
            slot: true,
            display: false,
            overHidden: true,
            hide: true,
          },
          {
            label: "区县",
            prop: "areaName",
            slot: true,
            display: false,
            overHidden: true,
            hide: true,
          },
          {
            label: "省份",
            prop: "province",
            type: "select",
            props: {
              label: "name",
              value: "code",
            },
            cascaderItem: ["city", "area"],
            dicUrl: "/api/blade-system/region/select",
            span: 8,
            showColumn: false,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择省份",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "地市",
            prop: "city",
            type: "select",
            props: {
              label: "name",
              value: "code",
            },
            dicUrl: "/api/blade-system/region/select?code={{key}}",
            span: 8,
            showColumn: false,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择地市",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "区县",
            prop: "area",
            type: "select",
            props: {
              label: "name",
              value: "code",
            },
            dicUrl: "/api/blade-system/region/select?code={{key}}",
            span: 8,
            showColumn: false,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择区县",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "详细地址",
            prop: "address",
            type: "textarea",
            span: 24,
            minRows: 2,
            hide: true,
            rules: [
              {
                required: true,
                message: "请输入详细地址",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 200
          },
          {
            label: "结算模式",
            prop: "settlementMode",
            type: "switch",
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=settlement_mode",
            dataType: "number",
            showColumn: false,
            slot: true,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            overHidden: true,
            minWidth:70
          },
          {
            label: "合作状态",
            prop: "isCooperate",
            type: "switch",
            width: 70,
            dicUrl: "/api/blade-system/dict/dictionary?code=is_cooperate",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            value: "1",
            slot: true,
            overHidden: true,
          },
          {
            label: "分润状态",
            prop: "profitState",
            span: 12,
            type: "radio",
            width: 91,
            dicUrl: "/api/blade-system/dict/dictionary?code=profit_state",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            value: "2",
            slot: true,
            overHidden: true,
          },
          {
            label: "合同状态",
            prop: "cooperateState",
            span: 12,
            type: "radio",
            width: 70,
            dicUrl: "/api/blade-system/dict/dictionary?code=cooperate_state",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            value: "0",
            slot: true,
            overHidden: true,
          },
          {
            label: "审核状态",
            prop: "serviceAuditStatus",
            span: 12,
            type: "radio",
            width: 80,
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=service_audit_status",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            slot: true,
            overHidden: true,
          },
          {
            label: "认证状态",
            prop: "isAuth",
            type: "switch",
            search: true,
            width: 80,
            dicUrl: "/api/blade-system/dict/dictionary?code=is_auth",
            dataType: "number",
            showColumn: false,
            slot: true,
            value: 1,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            overHidden: true,
          },
          {
            label: "结算卡状态",
            prop: "isBankAuthName",
            type: "input",
            width: 82,
            overHidden: true
          },
          {
            label: "结算卡状态",
            prop: "isBankAuth",
            type: "select",
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=is_bank_auth",
            dataType: "number",
            showColumn: false,
            slot: true,
            value: 1,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            overHidden: true,
            hide:true
          },
          // {
          //   label: "审核备注",
          //   prop: "auditResult",
          //   width: 150,
          //   span: 24,
          //   addDisplay: false,
          //   editDisplay: false,
          // },
          {
            label: "审核时间",
            prop: "auditTime",
            minWidth: 134,
            slot: true,
            span: 24,
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
          },
          {
            label: "创建时间",
            prop: "createTime",
            slot: true,
            span: 24,
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
            minWidth: 140
          },
        ],
      },
      data: [],
      oem: {},
      basicForm: {
        id: null,
        serviceName: "",
        serviceType: "",
        contactName: "",
        contactNumber: "",
        email: "",
        provinceCityArea: [],
        province: "",
        city: "",
        area: "",
        address: "",
        settlementMode: "",
        isCooperate: "1",
        profitState: "2",
        cooperateState: "0",
      },
      mainForm: {
        compName: "",
        roaName: "",
        roaCardNo: "",
        roaLicenseNo: "",
        roaLicenseTime: "",
        roaLicenseImage: "",
        roaCardPositive: "",
        roaCardBack: "",
        roaCardTime: "",
        roaCardStartTime:"",//法人身份证开始时间
        businessAddress:"",//营业执照地址
        roaLicenseStartTime:"",//营业执照开始时间
        roaCardHeld:"",//手持身份证
      },
      cardForm: {
        robBank: "",
        robBankBranch: "",
        robBankName: "",
        bankMobile: "",
        robBankNo: "",
        robBankPositive: "",
        robBankBack: "",
        robCardPublicImg: "",
        provinceCityArea: [],
        province: "",
        city: "",
        area: ""
      },
      aisleAllot: [], //通道分配 绑定value
      aisleData: [], //通道分配 数据
      serviceData: [], //服务商六合一数据
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/serviceinfo/service_info/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.service_info_add, false),
        viewBtn: this.vaildData(this.permission.service_info_view, false),
        delBtn: this.vaildData(this.permission.service_info_delete, false),
        editBtn: this.vaildData(this.permission.service_info_edit, false),
        menuBtn: this.vaildData(this.permission.service_menu, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    getColorServiceAuditStatus() {
      return state => {
        if (state == '0') {
          return '#E6A23C';
        } else if (state == '1') {
          return '#396afc';
        } else if (state == '2') {
          return '#67C23A';
        } else if (state == '3') {
          return '#F56C6C';
        }
      }
    },
    getColorState() {
      return state => {
        if (state.isAuth == '0') {
          return '#F56C6C';
        } else if (state.isAuth == '1') {
          return '#67C23A';
        }
      }
    },
    getColorIsCooperate() {
      return state => {
        if (state.isCooperate == '0') {
          return '#F56C6C';
        } else if (state.isCooperate == '1') {
          return '#67C23A';
        }
      }
    },
    getColorCooperateState() {
      return state => {
        if (state.cooperateState == '2') {
          return '#F56C6C';
        } else if (state.cooperateState == '1') {
          return '#E6A23C';
        } else if (state.cooperateState == '0') {
          return '#67C23A';
        }
      }
    },
    getColorProfitState() {
      return state => {
        if (state.profitState == '0') {
          return '#F56C6C';
        } else if (state.profitState == '1') {
          return '#E6A23C';
        } else if (state.profitState == '2') {
          return '#67C23A';
        }
      }
    },
    getColorIsBankAuthName() {
      return state => {
        if (state == '0') {
          return '#F56C6C';
        } else if (state == '1') {
          return '#67C23A';
        }
      }
    }
  },
  watch:{},
  methods: {
    /* 服务商表单 上一页 */
    handlePageUp() {
      if (this.active-- <= 0) this.active = 0;
      this.dialogSubmitBtnText = '下一页';
      switch (this.active) {
        case 0:
          getDetail({id: this.oem.id}).then((res) => {
            this.basicForm.id = res.data.data.id;
          });
          break;
        case 1:
          getAuthDetail(this.oem.userNo).then(res => {
            this.mainForm.id = res.data.data.id;
          });
          break;
        case 2:
          getBankDetail(this.oem.userNo).then(res => {
            this.cardForm.id = res.data.data.id;
          });
          break;
      }
    },
    /* 服务商表单 下一页 */
    handlePageDown() {
      const _this = this;
      switch (_this.active) {
        case 0:
          _this.basicSubmit(_this.dialogType);
          break;
        case 1:
          _this.mainSubmit(_this.dialogType);
          break;
        case 2:
          _this.cardSubmit(_this.dialogType);
          break;
        case 3:
          _this.aisleSubmit(_this.dialogType);
          break;
        case 4:
          _this.servicePolicySubmit(_this.dialogType);
          break;
        case 5:
          getFinish(this.oem.userNo).then((fini) => {
            if (fini.data.code == '200') {
              _this.emptyForm();
              _this.$message({
                type: "success",
                message: "服务商信息提交成功!",
              });
              _this.dialogVisible = false;
              _this.onLoad(_this.page);
            }
          }, error => {
            window.console.log(error);
          });
         
          break;
      }
    },
    /**
     * @func 关闭弹窗
     * @desc 点击关闭的回调
     * @param {Function} done - 完成的回调
     * */
    handleClose(done) {
      this.emptyForm();
      this.onLoad(this.page);
      done();
    },
    /* 服务商表单信息 清空 */
    emptyForm() {
      this.$refs["toBasicForm"].$refs["basicForm"].resetFields();
      this.$refs["toMainForm"].$refs["mainForm"].resetFields();
      this.$refs["toMainForm"].roaLicenseFileList = [];
      this.$refs["toMainForm"].roaPositiveFileList = [];
      this.$refs["toMainForm"].roaCardBackFileList = [];
      this.$refs["toMainForm"].roaCardHeldFileList =[];
      this.$refs["toCardForm"].$refs["cardForm"].resetFields();
      this.$refs["toCardForm"].robBankFileList = [];
      this.$refs["toCardForm"].robBackFileList = [];
      this.$refs["toCardForm"].robCardFileList = [];
      this.aisleData = [];
      this.aisleAllot = [];
    },
    emptyToMainForm(){
      this.$refs["toMainForm"].$refs["mainForm"].resetFields();
      this.$refs["toMainForm"].roaLicenseFileList = [];
      this.$refs["toMainForm"].roaPositiveFileList = [];
      this.$refs["toMainForm"].roaCardBackFileList = [];
      this.$refs["toMainForm"].roaCardHeldFileList =[];
    },
    emptyToCardForm(){
      this.$refs["toCardForm"].$refs["cardForm"].resetFields();
      this.$refs["toCardForm"].robBankFileList = [];
      this.$refs["toCardForm"].robBackFileList = [];
      this.$refs["toCardForm"].robCardFileList = [];
    },
    /**
     * @func 新增
     * @desc 点击新增初始化显示基本信息
     * */
    handleSave() {
      this.active = 0;
      this.dialogVisible = true;
      this.dialogType = "add";
      this.dialogText = "新增";
      this.dialogSubmitBtnText = '下一页';
      this.oem = {};
      this.basicForm.id = null
    },
    /**
     * @func 编辑
     * @desc 点击编辑回显基本信息
     * @param {Object} row - 表格绑定的信息
     * */
    handleEdit(row) {
      this.active = 0;
      this.dialogVisible = true;
      this.dialogType = "edit";
      this.dialogText = "编辑";
      this.dialogSubmitBtnText = '下一页';
      getDetail({id: row.id}).then((res) => {
        const data = res.data.data;
        data.serviceType = data.serviceType.toString();
        data.settlementMode = data.settlementMode.toString();
        data.isCooperate = data.isCooperate.toString();
        data.profitState = data.profitState.toString();
        data.cooperateState = data.cooperateState.toString();
        this.basicForm = data;
        this.$refs["toBasicForm"].isShow = false;
        this.$nextTick(() => {
          this.$refs["toBasicForm"].isShow = true;
          this.basicForm.provinceCityArea = [
            this.basicForm.province,
            this.basicForm.city,
            this.basicForm.area,
          ];
        });        
      });
    },
    /**
     * @func 菜单分配
     * @desc 点击编辑回显基本信息
     * @param {Object} row - 表格绑定的信息
     * */
    handleMenu(row) {
      this.dialogMenuVisible = true;
      this.serviceNo = row.serviceNo;
      this.$nextTick(() => {
        this.oem.tenantId = row.tenantId;
        this.$refs["toMenuGrant"].getMenuGrant("details", "2", {"userId": row.userId});
      })
    },
    /**
     * @func 详情
     * @desc 点击查看进入详情页
     * @param {Object} row - 服务商表格绑定信息
     * */
    handleView(row) {
      this.$router.push({
        name: "服务商详情",
        query: {
          id: row.id,
        },
      });
    },
    /**
     * @func 提交菜单
     * @desc 提交编辑后的菜单
     * */
    menuSubmit() {
      const menuList = this.$refs["toMenuGrant"].$refs.treeMenu.getCheckedKeys();
      const menudata = {
        "serviceNo": this.serviceNo,
        "menuIds": menuList
      }
      submitMenu(menudata).then((res) => {
        if (res.data.code == '200') {
          this.dialogMenuVisible = false;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        } else {
          this.$message({
            type: "error",
            message: res.data.message
          });
        }
      }, error => {
        window.console.log(error);
      });
    },
    /**
     * @func 服务商基本信息提交
     * @desc 提交实名信息
     * @param {String} type - 类型(新增/修改)
     * */
    basicSubmit(type) {
      // this.$refs["toMainForm"].roaLicenseFileList = [];
      // this.$refs["toMainForm"].roaPositiveFileList = [];
      // this.$refs["toMainForm"].roaCardBackFileList = [];
      if (type === "add") {
        this.$refs["toBasicForm"].$refs["basicForm"].validate((valid) => {
          if (valid) {
            this.basicForm.province = this.basicForm.provinceCityArea[0];
            this.basicForm.city = this.basicForm.provinceCityArea[1];
            this.basicForm.area = this.basicForm.provinceCityArea[2];
            this.basicForm.serviceKind = 1;

            add(this.basicForm).then(
              (res) => {
                this.oem = res.data.data;
                if (res.data.code == "200") {
                  this.$message({
                    type: "success",
                    message: "操作成功!"
                  });
                  this.emptyToMainForm();
                  if (this.active++ > 4) this.active = 0;
                } else {
                  this.$message({
                    type: "error",
                    message: res.data.message,
                  });
                }
              },
              (error) => {
                window.console.log(error);
              }
            );
          } else {
            return false;
          }
        });
      } else if (type === "edit") {
        this.$refs["toBasicForm"].$refs["basicForm"].validate((valid) => {
          if (valid) {
            this.basicForm.province = this.basicForm.provinceCityArea[0];
            this.basicForm.city = this.basicForm.provinceCityArea[1];
            this.basicForm.area = this.basicForm.provinceCityArea[2];
            this.basicForm.serviceKind = 1;
            update(this.basicForm).then(
              (res) => {
                this.oem = res.data.data;
                if (res.data.code == "200") {
                  getAuthDetail(this.oem.userNo).then(res => {
                    this.mainForm = res.data.data;
                    if (JSON.stringify(res.data.data) !== '{}') {
                      this.$refs["toMainForm"].roaLicenseFileList.length == 0 && res.data.data.roaLicenseImageUrl ? this.$refs["toMainForm"].roaLicenseFileList.push({url: res.data.data.roaLicenseImageUrl || ""}) : this.$refs["toMainForm"].roaLicenseFileList;
                      this.$refs["toMainForm"].roaPositiveFileList.length == 0 && res.data.data.roaCardPositiveUrl ? this.$refs["toMainForm"].roaPositiveFileList.push({url: res.data.data.roaCardPositiveUrl || ""}) : this.$refs["toMainForm"].roaPositiveFileList;
                      this.$refs["toMainForm"].roaCardBackFileList.length == 0 && res.data.data.roaCardBackUrl ? this.$refs["toMainForm"].roaCardBackFileList.push({url: res.data.data.roaCardBackUrl || ""}) : this.$refs["toMainForm"].roaCardBackFileList;
                      this.$refs["toMainForm"].roaCardHeldFileList.length == 0 && res.data.data.roaCardHeldUrl ? this.$refs["toMainForm"].roaCardHeldFileList.push({url: res.data.data.roaCardHeldUrl || ""}) : this.$refs["toMainForm"].roaCardHeldFileList; //法人手持身份证
                    }
                  });
                  this.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                  if (this.active++ > 4) this.active = 0;
                } else {
                  this.$message({
                    type: "error",
                    message: res.data.message,
                  });
                }
              },
              (error) => {
                window.console.log(error);
              }
            );
          } else {
            return false;
          }
        });
      }
    },
    /**
     * @func 服务商实名信息提交
     * @desc 提交实名信息
     * @param {String} type - 类型(新增/修改)
     * */
    mainSubmit(type) {
      // this.$refs["toCardForm"].robBankFileList = [];
      // this.$refs["toCardForm"].robBackFileList = [];
      // this.$refs["toCardForm"].robCardFileList = [];
      let that = this;
      if (type === "add") {
        this.$refs["toMainForm"].$refs["mainForm"].validate((valid) => {
          if (valid) {
            this.$set(this.mainForm, 'userNo', this.oem.userNo);

            authAdd(this.mainForm).then((res) => {
              if (res.data.code == '200') {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                this.emptyToCardForm();
                
                if(that.basicForm.serviceType == 0){
                  that.cardForm.robBankName = that.mainForm.roaName;
                }else{
                  that.cardForm.robBankName = that.mainForm.compName;
                }

                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            return false;
          }
        });
      } else if (type === "edit") {
        this.$refs["toMainForm"].$refs["mainForm"].validate((valid) => {
          if (valid) {
            this.$set(this.mainForm, 'userNo', this.oem.userNo);
            authUpdate(this.mainForm).then((res) => {
              if (res.data.code == '200') {
                getBankDetail(this.oem.userNo).then(res => {
                  this.cardForm = res.data.data;
                  
                  if(!this.cardForm.robBankName){
                    if(that.basicForm.serviceType == 0){
                      that.cardForm.robBankName = that.mainForm.roaName;
                    }else{
                      that.cardForm.robBankName = that.mainForm.compName;
                    }
                  }

                  if(this.cardForm.area){
                    this.$refs["toCardForm"].isShow = false;
                    this.$nextTick(()=>{
                      this.$refs["toCardForm"].isShow = true;
                      this.cardForm.provinceCityArea=[this.cardForm.province,this.cardForm.city,this.cardForm.area]
                    })
                  }
                  if (JSON.stringify(res.data.data) !== '{}') {
                    this.$refs["toCardForm"].robBankFileList.length == 0 && res.data.data.robBankPositiveUrl ? this.$refs["toCardForm"].robBankFileList.push({url: res.data.data.robBankPositiveUrl || ""}) : this.$refs["toCardForm"].robBankFileList;
                    this.$refs["toCardForm"].robBackFileList.length == 0 && res.data.data.robBankBackUrl ? this.$refs["toCardForm"].robBackFileList.push({url: res.data.data.robBankBackUrl || ""}) : this.$refs["toCardForm"].robBackFileList;
                    this.$refs["toCardForm"].robCardFileList.length == 0 && res.data.data.robCardPublicImgUrl ? this.$refs["toCardForm"].robCardFileList.push({url: res.data.data.robCardPublicImgUrl || ""}) : this.$refs["toCardForm"].robCardFileList;
                    // this.$refs["toCardForm"].roaCardHeldFileList.length == 0 && res.data.data.roaCardHeldUrl ? this.$refs["toCardForm"].roaCardHeldFileList.push({url: res.data.data.roaCardHeldUrl || ""}) : this.$refs["toCardForm"].roaCardHeldFileList; //法人手持身份证
                  }
                });
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            return false;
          }
        });
      }
    },
    /**
     * @func 服务商结算卡提交
     * @desc 提交结算卡信息
     * @param {String} type - 类型(新增/修改)
     * */
    cardSubmit(type) {
      this.aisleData = [];
      if (type === "add") {
        this.$refs["toCardForm"].$refs["cardForm"].validate((valid) => {
          if (valid) {
            
            if(this.cardForm.provinceCityArea){
              this.cardForm.province = this.cardForm.provinceCityArea[0];
              this.cardForm.city = this.cardForm.provinceCityArea[1];
              this.cardForm.area = this.cardForm.provinceCityArea[2];
            }

            this.$set(this.cardForm, 'userNo', this.oem.userNo);
            bankAdd(this.cardForm).then((res) => {
              if (res.data.code == '200') {
                getAisleOemList('-1', '-1').then(res => {
                  let aisleData = res.data.data.records;
                  aisleData.forEach((item, index) => {
                    this.aisleData.push({
                      label: item.aisleName,
                      key: item.aisleCode,
                      pinyin: item.aisleName[index]
                    });
                  });
                });
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });

                this.aisleAllot = [];
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          } else {
            return false;
          }
        });
      } else if (type === "edit") {
        this.$refs["toCardForm"].$refs["cardForm"].validate((valid) => {
          if (valid) {
            console.log(this.cardForm)
            if(this.cardForm.provinceCityArea){
              this.cardForm.province = this.cardForm.provinceCityArea[0];
              this.cardForm.city = this.cardForm.provinceCityArea[1];
              this.cardForm.area = this.cardForm.provinceCityArea[2];
            }

            this.aisleAllot = [];
            this.$set(this.cardForm, 'userNo', this.oem.userNo);
            bankUpdate(this.cardForm).then((res) => {
              if (res.data.code == '200') {
                getAisleOemList('-1', '-1').then(res => {
                  let aisleData = res.data.data.records;
                  aisleData.forEach((item, index) => {
                    this.aisleData.push({
                      label: item.aisleName,
                      key: item.aisleCode,
                      pinyin: item.aisleName[index]
                    });
                  });
                });
                getAisleOemList('-1', '-1', this.oem.userNo).then(res => {
                  let aisleAllots = res.data.data.records;
                  aisleAllots.forEach((item) => {
                    this.aisleAllot.push(item.aisleCode);
                  });
                });
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                if (this.active++ > 4) this.active = 0;
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            }, error => {
              window.console.log(error);
            });
          }
        });
      }
    },
    /**
     * @func 服务商通道提交
     * @desc 根据可选通道分配通道提交
     * @param {String} type - 类型(新增/修改)
     * */
    aisleSubmit(type) {
      if (this.aisleAllot.length > 0) {
        if (type) {
          if (this.active++ > 4) this.active = 0;
        }
        /* 弃用 更改日期 2022年11月16日 详情通道政策与此同步修改 */
        /* if (type === "add") {
          let aisleDatas = {
            "aisleCodes": this.aisleAllot,
            ...this.oem
          }
          aisleAdd(aisleDatas).then((res) => {
            if (res.data.code == '200') {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              if (this.active++ > 4) this.active = 0;
            } else {
              this.$message({
                type: "error",
                message: res.data.message
              });
            }
          }, error => {
            window.console.log(error);
          });
        } else if (type === "edit") {
          let aisleDatas = {
            "aisleCodes": this.aisleAllot,
            ...this.oem
          }
          aisleUpdate(aisleDatas).then((res) => {
            if (res.data.code == '200') {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              if (this.active++ > 4) this.active = 0;
            } else {
              this.$message({
                type: "error",
                message: res.data.message
              });
            }
          }, error => {
            window.console.log(error);
          });
        } else {
          return false;
        } */
      } else {
        this.$message({
          type: "warning",
          message: "请先选择通道!",
        });
      }
    },
    /**
     * @func 服务商政策分润提交
     * @desc 根据已分配通道处理政策阶梯分润提交
     * @param {String} type - 类型(新增/修改)
     * */
    servicePolicySubmit(type) {
      if (type === "add") {
        let policyDatas = {
          "policyList": this.$refs['toPolicyForm'].data,
          ...this.oem
        }
        policyUpdateAll(policyDatas).then((res) => {
          if (res.data.code == '200') {
            // getFinish(this.oem.userNo).then((fini) => {
            //   if (fini.data.code == '200') {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                // if (this.active++ > 4) this.active = 0;
                this.dialogSubmitBtnText = '提 交';
                this.getAllDetails(this.oem.id);
              // }
            // }, error => {
            //   window.console.log(error);
            // });
          } else {
            this.$message({
              type: "error",
              message: res.data.message
            });
          }
        }, error => {
          window.console.log(error);
        });
      } else if (type === "edit") {
        let policyDatas = {
          "policyList": this.$refs['toPolicyForm'].data,
          ...this.oem
        }
        policyUpdateAll(policyDatas).then((res) => {
          if (res.data.code == '200') {
            // getFinish(this.oem.userNo).then((fini) => {
            //   if (fini.data.code == '200') {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                // if (this.active++ > 4) this.active = 0;

                this.dialogSubmitBtnText = '提 交';
                this.getAllDetails(this.oem.id);
            //   }
            // }, error => {
            //   window.console.log(error);
            // });
          } else {
            this.$message({
              type: "error",
              message: res.data.message
            });
          }
        }, error => {
          window.console.log(error);
        });
      }
    },
    /* 租户详情接口 */
    getAllDetails(id) {
      getServiceDetail(id).then((res) => {
        let data = res.data.data;
        data.baseInfo.serviceType = data.baseInfo.serviceType + "";
        data.baseInfo.settlementMode = data.baseInfo.settlementMode + "";
        data.baseInfo.isCooperate = data.baseInfo.isCooperate + "";
        data.baseInfo.cooperateState = data.baseInfo.cooperateState + "";
        data.baseInfo.profitState = data.baseInfo.profitState + "";
        data.baseInfo.provinceCityArea = [
          data.baseInfo.province,
          data.baseInfo.city,
          data.baseInfo.area,
        ];
        this.$nextTick(()=>{
          this.serviceData = data;
          if (this.active++ > 4) this.active = 0;
        })
      });
    },
    rowSave(row, done, loading) {
      //合同等状态 初始化赋值
      row.isCooperate = this.form.isCooperate;
      row.profitState = this.form.profitState;
      row.cooperateState = this.form.cooperateState;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.openType = type;
      if (["edit", "view"].includes(type)) {
        getDetail({id: this.form.id}).then((res) => {
          this.form = res.data.data;
          this.form.isCooperate = res.data.data.isCooperate + "";
          this.form.profitState = res.data.data.profitState + "";
          this.form.cooperateState = res.data.data.cooperateState + "";
        });
      }
      done();
    },
    /**
     * @func 菜单权限树形是否禁止
     * @desc dialog打开类型为 view 则禁止权限树
     * @param {String} openType - 打开类型
     * */
    isDisabledFn() {
      const _this = this;
      if (["view"].includes(_this.openType)) {
        return true;
      }
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        page.serviceKind,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    /* 服务商 导出excel */
    handleExport() {
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getExport(this.search).then((res) => {
            downloadFileExcel(res);
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },
    /* 服务商 导出模板excel */
    handleTemplate() {
      getExportTemplate().then((res) => {
          downloadFileExcel(res);
        },
        (error) => {
          window.console.log(error);
        }
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  }
};
</script>

<style lang="scss" scoped>
/deep/.el-transfer-panel__list.is-filterable{
  width: 400px !important;
  height: 500px !important;
}
 
/deep/.el-transfer-panel{
  width: 400px !important;
  height: 500px !important;
}
/deep/ .el-tag--dark.el-tag--success {
  border-color: transparent;
  opacity: 0.8;
}
</style>
